package il.technion.cs236369.threadPool;

import il.technion.cs236369.interfaces.IObservable;
import il.technion.cs236369.interfaces.IObserver;

/**
 * A timer thread that runs a specified amount of time and then notifies when
 * the time is over USE: Start the new timer thread. Set the observer to be
 * called when the timer is done. Notify it to begin the timer. Interrupt the
 * thread to stop the timer.
 * 
 * @author Gal Lalouche
 * 
 */
public class TimerThread extends Thread implements IObservable {
	private final Integer	_timeoutTime;

	private IObserver	_observer;

	/**
	 * Creates a new timer thread
	 * @param timeoutTime The time to measure (use null for infinite, this is essentially a null object pattern)
	 */
	public TimerThread(Integer timeoutTime) {
		setDaemon(true);
		_timeoutTime = timeoutTime;
	}

	@Override
	public void run() {
		if (_timeoutTime == null) {
			return;
		}
		
		while (true) {
			try {
				// wait for new requests
				synchronized (this) {
					wait();
				}
				// start the timer
				Thread.sleep(_timeoutTime);
				// notify the observer that the timer has finished
				if (_observer != null) {
					_observer.notifyObserver();
				}
			} catch (InterruptedException e) {
				// do nothing, task finished in time
			}
		}
	}

	@Override
	public void setObservable(IObserver observer) {
		_observer = observer;
	}
}
